package com.app.controller.backstage;

import com.app.model.AdminUserModel;
import com.app.model.EntrepreneurshipModel;
import com.app.model.UserModel;
import com.app.model.VillageFairModel;
import com.app.service.*;
import com.app.util.Result;
import com.app.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@Controller
@RequestMapping("/admin")
public class UserManageController {
    @Autowired
    private UserService userService;
    @Autowired
    private EntrepreneurshipService entrepreneurshipService;
    @Autowired
    private VillageFairService villageFairService;
    @Autowired
    private AdminUserService adminUserService;

    //用户列表
    @GetMapping("/userList")
    public Result<Object> userList(Integer page, Integer limit, String keyword) {
        return Result.success(userService.getList(page, limit, keyword));
    }

    //删除用户
    @GetMapping("/deleteUser")
    public Result<Object> deleteUser(Integer id, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        userService.deleteById(id);
        return Result.success("删除成功");
    }

    //修改状态
    @GetMapping("/updateStatus")
    public Result<Object> updateStatus(Integer id, Integer status, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        userService.updateStatus(id, status);
        return Result.success("修改成功");
    }

    //查询个人信息
    @GetMapping("/selectUserById")
    public Result<Object> selectUserById(Integer id) {
        UserModel model = userService.selectUserById(id);
        List<EntrepreneurshipModel> entrepreneurshipModels = entrepreneurshipService.selectByUserId(id);
        List<VillageFairModel> villageFairModels = villageFairService.selectByUserId(id);
        model.setEntrepreneurshipModels(entrepreneurshipModels);
        model.setVillageFairModels(villageFairModels);
        return Result.success(model);
    }
}
